<?php echo $this->Session->flash(); ?>
<?php

App::import('Vendor', 'ClassEzpdf', array('file' => 'pdf/class.ezpdf.php'));
$pdf = new Cezpdf('LETTER');
App::import('model', 'Proyect');
$proyecto = new Proyect();
$pdf->ezStartPageNumbers(20, 55, 10, 'right', utf8_decode('Página' . "  {PAGENUM} de {TOTALPAGENUM}"), 1);
generar_cartaev(' ', "", $pdf);
$sql = "SELECT Branch.* from proyects Proyect LEFT JOIN branches Branch ON Proyect.branch_id=Branch.id WHERE Proyect.id=$id";
$rbranc = $proyecto->query($sql);
foreach ($rbranc as $row6) {
    $bciudad = $row6['Branch']['nombre'];
    $director = $row6['Branch']['director'];
}

$sql = "SELECT Proposer.`nombre`,Proposer.`direccion`, Proposer.`telefono_fijo`, Proposer.`telefono_celular`,Proposer.`numero_identificacion`,Proposer.`proposer_type`,Proposer.`rep_nombres`,Proposer.`rep_cedula`, Proposer.`rep_apellidos`,City.name as ciudad,Departament.name as departamento FROM `proposers` Proposer  LEFT JOIN  cities City ON (Proposer.`city_id`=City.id) LEFT JOIN  departaments Departament ON (City.`departament_id`=Departament.id) WHERE Proposer.proyect_id=$id";
$rprop = $proyecto->query($sql);
$pdf->ezText("2500 \n", 11, array('justification' => 'left'));

foreach ($rprop as $row5) {
    $nom = $row5['Proposer']['nombre'];
    $dir = utf8_encode($row5['Proposer']['direccion']);
    $dep = utf8_encode($row5['Departament']['departamento']);
    $ciu = utf8_encode($row5['City']['ciudad']);
    $fj = $row5['Proposer']['telefono_fijo'];
    $cel = $row5['Proposer']['telefono_celular'];
    $txt = "Señor(a):\n$nom \nProponente Proyecto $codigo \nCONVOCATORIA PÚBLICA INCODER SIT-01-2011\n";
    $txt.="$dir $dep-$ciu \ntélefono: $fj  $cel \n";
}

$pdf->ezText(utf8_decode($txt), 11, array('justification' => 'left'));
//$pdf->ezText( "$bciudad\n",11, array('justification'=>'left'));

$data = array();
$data[] = array('uno' => utf8_decode("<b>Referencia:</b> Observación y Requerimiento de la propuesta $codigo presentada a la Convocatoria Pública INCODER SIT-01-2011."));
$pdf->ezTable(
        $data, null, "", array(
    'fontSize' => 10,
    'titleFontSize' => 10,
    'width' => 470,
    'protectRows' => 20,
    'showHeadings' => 0,
    'showLines' => 2,
    'shaded' => 0,
    'cols' => array('uno' => array('justification' => 'full'))
        )
);
$pdf->ezText("\n", 10, array('justification' => 'left'));

$str = "De conformidad con lo establecido en los términos de referencia de la Convocatoria Pública para el Otorgamiento del Subsidio Integral para la Compra de Tierras INCODER SIT-01-2011, el Instituto tiene la facultad para solicitar documentos adicionales, en este orden de ideas nos permitimos realizar las siguientes Observaciones y Requerimientos:\n";
$pdf->ezText(utf8_decode("\n$str"), 10, array('justification' => 'full'));
$fl = 1;


foreach ($proyectos as $pro) {
    switch ($pro['ProyectRequirement']['calificacion']) {
        case 1:
            $cal = "Cumple";
            break;
        case 2:
            $cal = "No Cumple";
            break;
        case 3:
            $cal = "Subsanable";
            break;
        default:
            $cal = "Sin Registro";
            break;
    }

    if ($cal == 'Subsanable') {
        if ($fl == 1) {
            $pdf->ezText(" FILTRO PROYECTO\n", 12, array('justification' => 'center'));
            $fl = 0;
        }
        $data[] = array(
            'uno' => utf8_decode($pro['Requirement']['texto']),
            'dos' => $cal
        );
        $pdf->ezTable(
                $data, null, "", array(
            'fontSize' => 8,
            'titleFontSize' => 10,
            'width' => 470,
            'protectRows' => 20,
            'showHeadings' => 0,
            'showLines' => 2,
            'shaded' => 2,
            'cols' => array('uno' => array('justification' => 'full'), 'dos' => array('justification' => 'full', 'width' => 60))
                )
        );

        $reqF = array();
        foreach ($pro['RequirementFault'] as $fault) {

            $reqF[] = array('uno' => utf8_decode($fault['nombre']), 'dos' => utf8_decode($fault['respuesta']));
        }
        $pdf->ezTable(
                $reqF, null, "", array(
            'fontSize' => 8,
            'titleFontSize' => 10,
            'width' => 470,
            'protectRows' => 5,
            'showHeadings' => 0,
            'showLines' => 2,
            'shaded' => 0,
            'cols' => array('uno' => array('justification' => 'full'), 'dos' => array('justification' => 'full'))
                )
        );
    }
}

//FILTRO ASPIRANTES


$cand = $proyecto->query("SELECT * FROM candidates Candidate WHERE proyect_id=$id");
$primer = 1;
foreach ($cand as $row) {
    //$pdf->ezText("\n",12, array('justification'=>'center'));
    $flnon = 0;
    $asp = array();
    $candidate_id = $row['Candidate']['id'];
    $sql = "SELECT CandidateRequirement.id, CandidateRequirement.calificacion,Requirement.texto FROM `candidates` Candidate LEFT JOIN candidate_requirements CandidateRequirement ON ( Candidate.id = CandidateRequirement.candidate_id )LEFT JOIN requirements Requirement on(CandidateRequirement.requirement_id=Requirement.id) WHERE CandidateRequirement.candidate_id=$candidate_id AND CandidateRequirement.claim_id =$claim_id";
    $req = $proyecto->query($sql);


    foreach ($req as $row1) {

        $reqA = array();
        switch ($row1['CandidateRequirement']['calificacion']) {
            case 1:
                $cal = "Cumple";
                break;
            case 2:
                $cal = "No Cumple";
                break;
            case 3:
                $cal = "Subsanable";
                break;
            default:
                $cal = "Sin Registro";
                break;
        }
        if ($row1['CandidateRequirement']['calificacion'] == 2) {
            
        } elseif ($row1['CandidateRequirement']['calificacion'] == 3) {

            if ($primer == 1)
                $pdf->ezText("\nFILTRO ASPIRANTES", 12, array('justification' => 'center'));
            $primer = 0;
            if ($flnon == 0) {
                $pdf->ezText("\n" . utf8_decode($row['Candidate']['1er_nombre']) . " " . utf8_decode($row['Candidate']['2do_nombre']) . " " . utf8_decode($row['Candidate']['1er_apellido']) . " " . utf8_decode($row['Candidate']['2do_apellido']) . ' DOCUMENTO: ' . $row['Candidate']['nro_ident'] . "\n", 12, array('justification' => 'center'));
                $flnon = 1;
            }


            $reqA[] = array('Requisito' => utf8_decode($row1['Requirement']['texto']), 'Calificacion' => $cal);
            $pdf->ezTable(
                    $reqA, null, "", array(
                'fontSize' => 8,
                'titleFontSize' => 10,
                'width' => 470,
                'protectRows' => 5,
                'showHeadings' => 0,
                'showLines' => 2,
                'shaded' => 2,
                'cols' => array('Requisito' => array('justification' => 'full'), 'Calificacion' => array('justification' => 'full', 'width' => 60))
                    )
            );
            $fault_id = $row1['CandidateRequirement']['id'];
            $sql = "SELECT * FROM `requirement_faults` Requerimiento LEFT JOIN candidate_requirements_requirement_faults Subsanacion on Requerimiento.id=Subsanacion.requirement_fault_id WHERE Subsanacion.candidate_requirement_id=$fault_id";
            $caReqF = $proyecto->query($sql);
            $faultR = array();
            foreach ($caReqF as $row2) {
                switch ($row2['Requerimiento']['tipo']) {
                    case 1:
                        $cal = "Cumple";
                        break;
                    case 2:
                        $cal = "No Cumple";
                        break;
                    case 3:
                        $cal = "Subsanable";
                        break;
                    default:
                        $cal = "Sin Registro";
                        break;
                }

                $faultR[] = array('Aspecto' => utf8_decode($row2['Requerimiento']['nombre']), 'Solicitud' => utf8_decode($row2['Requerimiento']['respuesta']));
            }

            $pdf->ezTable(
                    $faultR, null, "", array(
                'fontSize' => 6,
                'titleFontSize' => 10,
                'width' => 470,
                'protectRows' => 5,
                'showHeadings' => 0,
                'showLines' => 2,
                'shaded' => 0,
                'cols' => array('Aspecto' => array('justification' => 'full', 'width' => 235), 'Solicitud' => array('justification' => 'full', 'width' => 235))
                    )
            );
        }
    }
}
//FIN FILTRO ASPIRANTES
// Filtro Predios
$predios = 1;
$properties = $proyecto->query("SELECT Property.id ,Property.codigo ,Property.nombre ,Property.matricula FROM properties Property  WHERE proyect_id=$id");



foreach ($properties as $row) {
    $nomp = 0;
    $asp = array();
    $prop_id = $row['Property']['id'];
    $sql = "SELECT Propertyrequirement.id, Propertyrequirement.calificacion,Requirement.texto,Propertyrequirement.concepto FROM `properties` Property LEFT JOIN property_requirements Propertyrequirement  ON ( Property.id = Propertyrequirement.property_id )LEFT JOIN requirements Requirement on(Propertyrequirement.requirement_id=Requirement.id) WHERE Propertyrequirement.property_id=$prop_id AND Propertyrequirement.claim_id =$claim_id";
    $req = $proyecto->query($sql);


    foreach ($req as $row1) {
        $reqA = array();
        switch ($row1['Propertyrequirement']['calificacion']) {
            case 1:
                $cal = "Cumple";
                break;
            case 2:
                $cal = "No Cumple";
                break;
            case 3:
                $cal = "Subsanable";
                break;
            default:
                $cal = "Sin Registro";
                break;
        }
        if ($row1['Propertyrequirement']['calificacion'] == 3) {

            if ($predios == 1) {
                $pdf->ezText("\n FILTRO PREDIOS \n ", 12, array('justification' => 'center'));
                $predios = 0;
            }
            if ($nomp == 0) {
                $pdf->ezText("\n" . utf8_decode($row['Property']['codigo']) . " " . utf8_decode($row['Property']['nombre']) . " " . " MATRICULA: " . $row['Property']['matricula'] . "\n", 12, array('justification' => 'center'));
                $nomp = 1;
            }


            // $pdf->ezText("\n",12, array('justification'=>'center'));
            $reqA[] = array('Requisito' => utf8_decode($row1['Requirement']['texto']), 'Calificacion' => $cal);
            if ($row1['Requirement']['texto'] != " ")
                $reqA[] = array('Requisito' => utf8_decode($row1['Propertyrequirement']['concepto']), 'Calificacion' => "");

            $pdf->ezTable(
                    $reqA, null, "", array(
                'fontSize' => 8,
                'titleFontSize' => 10,
                'width' => 470,
                'protectRows' => 0,
                'showHeadings' => 0,
                'showLines' => 2,
                'shaded' => 2,
                'cols' => array('Requisito' => array('justification' => 'full'), 'Calificacion' => array('justification' => 'full', 'width' => 60))
                    )
            );
            $fault_id = $row1['Propertyrequirement']['id'];
            $sql = "SELECT * FROM `requirement_faults`  Requisito LEFT JOIN property_requirements_requirement_faults Subsanacion on Requisito.id=Subsanacion.requirement_fault_id WHERE Subsanacion.property_requirement_id=$fault_id";
            $caReqF = $proyecto->query($sql);
            $faultR = array();
            foreach ($caReqF as $row2) {
                switch ($row2['Requisito']['tipo']) {
                    case 1:
                        $cal = "Cumple";
                        break;
                    case 2:
                        $cal = "No Cumple";
                        break;
                    case 3:
                        $cal = "Subsanable";
                        break;
                    default:
                        $cal = "Sin Registro";
                        break;
                }

                $faultR[] = array('Aspecto' => utf8_decode($row2['Requisito']['nombre']), 'Calificacion' => utf8_decode($row2['Requisito']['respuesta']));
            }

            $pdf->ezTable(
                    $faultR, null, "", array(
                'fontSize' => 8,
                'titleFontSize' => 10,
                'width' => 470,
                'protectRows' => 0,
                'showHeadings' => 0,
                'showLines' => 2,
                'shaded' => 0,
                'cols' => array('Aspecto' => array('justification' => 'full', 'width' => 235), 'Calificacion' => array('justification' => 'full', 'width' => 235))
                    )
            );
        }
    }



    $sql = "SELECT Title.id,Title.calificacion,Title.id,Title.concepto,Title.doc_subsanacion, Property.codigo FROM title_studies  Title LEFT JOIN properties Property on Title.property_id=Property.id WHERE Title.property_id =$prop_id And Title.id=(SELECT max(id) FROM title_studies WHERE property_id=$prop_id )";
    $studies = $proyecto->query($sql);
    $title = array();
    $titleInt = array();
    $titleF = array();
    foreach ($studies as $row3) {
        switch ($row3['Title']['calificacion']) {
            case 1:
                $cal = "Cumple";
                break;
            case 2:
                $cal = "No Cumple";
                break;
            case 3:
                $cal = "Subsanable";
                break;
            default:
                $cal = "Sin Registro";
                break;
        }
        if ($row3['Title']['calificacion'] == 3) {
            $pdf->ezText("\n", 12, array('justification' => 'center'));
            if ($predios == 1)
                $pdf->ezText("\n FILTRO PREDIOS \n", 12, array('justification' => 'center'));
            $predios = 0;
            $titleInt[] = array('uno' => utf8_decode('Calificación'), 'dos' => $cal);
            $titleInt[] = array('uno' => 'Concepto', 'dos' => utf8_decode($row3['Title']['concepto']));


            $titleInt[] = array('uno' => utf8_decode('Documentos Para subsabnación: '), 'dos' => utf8_decode($row3['Title']['doc_subsanacion']));
            $tit_id = $row3['Title']['id'];

            $pdf->ezTable(
                    $titleInt, null, "ESTUDIO DE TITULOS " . utf8_decode($row3['Property']['codigo']), array(
                'fontSize' => 8,
                'titleFontSize' => 10,
                'width' => 470,
                'protectRows' => 5,
                'showHeadings' => 0,
                'showLines' => 2,
                'shaded' => 0,
                'cols' => array('uno' => array('justification' => 'full'), 'dos' => array('justification' => 'full'))
                    )
            );
        }
    }
}
///ESTUDIO DE TITULOS
$pdf->ezNewPage();
$str = "\nLos documentos solicitados deben ser aportados por usted dentro de un plazo máximo de quince días calendario, contados a partir de la publicación en cartelera de la Dirección Territorial ";
$pdf->ezText(utf8_decode($str), 10, array('justification' => 'full'));
$str = "$bciudad.\n\n";
$pdf->ezText($str, 10, array('justification' => 'full'));
$str = "Tenga en cuenta que la propuesta tiene calidad de inmodificable por lo tanto debe aportar los documentos exclusivamente ";
$str.="solicitados y no serán admitidos cambios sustanciales en la propuesta\n";
$str.="\nCordialmente,\n\n\n\n\n" . $director;
$pdf->ezText(utf8_decode($str), 10, array('justification' => 'full'));
$str = "\nDirector Territorial " . $bciudad . "\n";
$pdf->ezText(utf8_decode($str), 10, array('justification' => 'full'));


$pdf->ezStopPageNumbers(1, 1, 0);
$pdf->ezStream();
?>
<?php

function generar_cartaev($cod, $str, &$pdf, $start = true, $m_left = 2.5, $m_right = 2.5) {
    App::import('Vendor', 'ClassEzpdf', array('file' => 'pdf/class.ezpdf.php'));
    if ($pdf == NULL) {
        $pdf = new Cezpdf('LETTER');
    }
    if ($start) {
        $tmp = array(
            'b' => 'Trebuchet-Bold.afm'
            , 'i' => 'Trebuchet-Italic.afm'
            , 'bi' => 'Trebuchet-BoldItalic.afm'
            , 'ib' => 'Trebuchet-BoldItalic.afm'
            , 'bb' => 'Trebuchet-Bold.afm'
        );
        $pdf->setFontFamily('Trebuchet.afm', $tmp);
        $pdf->selectFont('fonts/Trebuchet.afm');

        //$pdf->ezSetCmMargins(5.5,5.5,4,4);

        $all = $pdf->openObject();
        $pdf->saveState();
        $pdf->addPngFromFile('img/cabecera.png', 60, 670, 500);
        $pdf->addPngFromFile('img/linea_pie.png', 10, 0, 590, 50);
        $pdf->restoreState();
        $pdf->closeObject();
        $pdf->addObject($all, 'all');
        $pdf->transaction('start');
    }

    $pdf->ezSetCmMargins(5, 2.5, $m_left, $m_right);

    $textOptions = array('justification' => 'full');
    $data = explode("\n", $str);
    $collecting = 0;
    foreach ($data as $d) {
        chop($d);
        if (strlen($d) && $d[0] == '#') {
            // comment, or new page request
            switch ($d) {
                case '#NP':
                    $pdf->ezNewPage();
                    break;
            }
        } else {
            $pdf->ezText($d, 8, $textOptions);
        }
    }
}

?>